<template>
    <el-dialog :close-on-click-modal="false" :title="titleMap[mode]" v-model="visible" :width="1000" destroy-on-close @closed="visible = false" custom-class="notpt">

        <div style="height:100%;overflow-y: auto;overflow-x: hidden;">
            <div class="custom-box">
                <el-steps
                    :active="stepActive"
                    align-center
                    class="custom-stepActive"
                >
                    <el-step title="基础信息"></el-step>
                    <el-step title="附件信息"></el-step>
                </el-steps>
            </div>
        </div>

        <div class="cotent">
            <el-form :model="form" :rules="rules" :disabled="mode=='show'" ref="dialogForm" label-width="130px" label-position="right" v-loading="loading">
                <!-- 基础信息 -->
                <div v-show="stepActive == 1">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="归属机构" prop="parentId">
                                <el-select
                                style="width: 100%;"
                                v-model="form.parentId"
                                filterable
                                remote
                                clearable
                                placeholder="请输入机构名称搜索"
                                :remote-method="searchAgentHander"
                                @change="parentAgentChangeHander"
                                :loadings="agentLoading">
                                    <el-option
                                        v-for="item in agentList"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id"
                                        :disabled="item.disabled">
                                    </el-option>
                                </el-select>
                             </el-form-item>
                            <el-form-item label="名称" prop="name">
                                <el-input v-model="form.name" placeholder="请输入名称" clearable :maxlength="50" show-word-limit></el-input>
                            </el-form-item>
                            <el-form-item label="机构级别" prop="levelId">
                                <el-select
                                style="width: 100%;"
                                v-model="form.levelId"
                                filterable
                                clearable
                                @change="levelChangeHander"
                                >
                                    <el-option
                                        v-for="item in agentLevels"
                                        :key="item.id"
                                        :label="item.name"
                                        :value="item.id">
                                    </el-option>
                                </el-select>
                             </el-form-item>
                            <el-form-item label="负责人姓名" prop="chargeName">
                                <el-input v-model="form.chargeName" placeholder="请输入负责人姓名" clearable :maxlength="11" show-word-limit></el-input>
                            </el-form-item>
                            <el-form-item label="负责人手机号" prop="chargeMobile">
                                <el-input v-model="form.chargeMobile" placeholder="请输入负责人手机号" clearable :maxlength="11" show-word-limit></el-input>
                            </el-form-item>
                            <el-form-item label="管理员姓名" prop="manager">
                                <el-input v-model="form.manager" placeholder="请输入管理员姓名" clearable :maxlength="20" show-word-limit></el-input>
                            </el-form-item>
                            <el-form-item label="管理员手机号" prop="managerMobile">
                                <el-input v-model="form.managerMobile" placeholder="请输入管理员手机号" clearable :maxlength="11" show-word-limit></el-input>
                            </el-form-item>
                            <el-form-item label="开户人姓名" prop="bankUserName">
                                <el-input v-model="form.bankUserName" placeholder="请输入开户人姓名" clearable :maxlength="100" show-word-limit></el-input>
                            </el-form-item>
                            <el-form-item label="开户银行全称" prop="bankFullName">
                                <el-input v-model="form.bankFullName" placeholder="请输入开户银行全称" clearable :maxlength="200" show-word-limit></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                             <el-form-item label="60分钟课时" prop="classHour60">
                                <el-input v-model="form.classHour60" placeholder="60分钟课时" :disabled="true"></el-input>
                            </el-form-item>
                            <el-form-item label="收费金额" prop="amount">
                                <el-input v-model="form.amount" placeholder="收费金额" clearable :disabled="true">
                                    <template #append>元</template>
                                </el-input>
                            </el-form-item>
                            <el-form-item label="负责人身份证号" prop="chargeIdCard">
                                <el-input v-model="form.chargeIdCard" placeholder="请输入负责人身份证号" clearable></el-input>
                            </el-form-item>
                            <el-form-item label="管理员身份证号" prop="managerIdCard">
                                <el-input v-model="form.managerIdCard" placeholder="请输入管理员身份证号" clearable></el-input>
                            </el-form-item>
                            <el-form-item label="推荐人姓名" prop="promoterName">
                                <el-input v-model="form.promoterName" placeholder="请输入推荐人姓名" clearable :maxlength="20" show-word-limit></el-input>
                            </el-form-item>
                            <el-form-item label="推荐人手机号" prop="promoterMobile">
                                <el-input v-model="form.promoterMobile" placeholder="请输入推荐人手机号" clearable :maxlength="11" show-word-limit></el-input>
                            </el-form-item>
                            <el-form-item label="地区" prop="region">
                                <el-cascader style="width:100%;" :show-all-levels="true" size="small" placeholder="请选择" clearable :emitPath="false" :props="{
                                                value: 'id',
                                                label: 'name',
                                                emitPath: true
                                            }" v-model="form.region" :options="areaData"
                                        ></el-cascader>
					        </el-form-item>
                            <el-form-item label="详细地址" prop="address">
                                <el-input v-model="form.address" placeholder="请输入详细地址" clearable :maxlength="255" show-word-limit></el-input>
                            </el-form-item>
                            <el-form-item label="银行卡号" prop="bankCode">
                                <el-input v-model="form.bankCode" placeholder="请输入银行卡号" clearable :maxlength="200" show-word-limit></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>
                <!-- 附件信息 -->
                <div v-show="stepActive == 2">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="本人照片" prop="image">
                                <sc-upload v-model="form.image" title="上传图片" cropper :aspectRatio="1/1"></sc-upload>
                            </el-form-item>
                            <el-form-item label="转账记录" prop="paymentImg">
                                <sc-upload v-model="form.paymentImg" title="上传图片" ></sc-upload>
                            </el-form-item>
                            <el-form-item label="身份证正反面" prop="idCardImg">
                                <scUploadMultiple v-model="form.idCardImg" title="上传图片" :limit="2"></scUploadMultiple>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="推荐人合影" prop="promoterImg">
                                <sc-upload v-model="form.promoterImg" title="上传图片"></sc-upload>
                            </el-form-item>
                            <el-form-item label="合同照片" prop="contractImg">
                                <sc-upload v-model="form.contractImg" title="上传图片"></sc-upload>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>
            </el-form>
        </div>

         <template #footer>
            <el-button @click="visible = false">关闭</el-button>
            <el-button type="primary" @click="prevHander" v-if="stepActive == 2">上一步</el-button>
            <el-button @click="submit" type="primary" v-if="stepActive == 2" :loading="isSaveing">保存</el-button>
            <el-button type="primary" @click="nextHander" v-if="stepActive == 1">下一步</el-button>
        </template>

    </el-dialog>
</template>

<script>
import { checkMobile } from '@/utils/validate'
export default {
    emits: ['success', 'closed'],
    props: {
        agentCategorys: { type: Array, default: () => [] },
        areaData: { type: Array, default: () =>  [] },
    },
    data() {
        return {
            mode: "add",
            loading: false,
            visible: false,
            isSaveing: false,
            agentLoading: false,
            titleMap: {
                add: '新增开户申请',
                edit: '编辑开户申请',
                show: '查看'
            },
            stepActive: 1,
            totalStep: 2,
            form: this.getDefaultRuleForm(),
            rules: {
                levelId: [
                    { required: true, message: '请选择机构等级', trigger: 'change' }
                ],
                parentId: [
                    { required: true, message: '请选择归属机构', trigger: 'change' }
                ],
                image: [
                    { required: true, message: '请上传本人照片' }
                ],
                name: [
                    { required: true, message: '请输入名称' }
                ],
                amount: [
                    { required: true, message: '请输入收费金额' },
                    { pattern: /^0\.([0-9]|\d[0-9])$|^[0-9]\d{0,8}\.\d{0,2}$|^[0-9]\d{0,8}$/, message: '只能输入数字且最多只有2位小数', trigger: 'blur'},
                ],
                manager: [
                    { required: true, message: '请输入管理员姓名' }
                ],
                managerMobile: [
                    { required: true, validator: checkMobile }
                ],
                managerIdCard: [
                    { required: true, message: '请输入管理员身份证号' }
                ],
                chargeName: [
                    { required: true, message: '请输入负责人姓名' }
                ],
                chargeMobile: [
                    { required: true, validator: checkMobile }
                ],
                chargeIdCard: [
                    { required: true, message: '请输入负责人身份证号' }
                ],
                region: [
					{ required: true, message: '请选择地区' }
				],
                address: [
					{ required: true, message: '请输入详细地址' }
				],
                promoterName: [
                    { required: false, message: '请输入推荐人姓名' }
                ],
                promoterMobile: [
                    { required: false, validator: checkMobile }
                ],
                idCardImg: [
                    { required: true, message: '请上传身份证正反面' }
                ],
                promoterImg: [
                    { required: false, message: '请上传推荐人合影' }
                ],
                paymentImg: [
                    { required: true, message: '请上传转账记录' }
                ],
                contractImg: [
                    { required: true, message: '请上传合同照片' }
                ],
                bankFullName: [
                    { required: true, message: '请输入开户行全称' }
                ],
                bankUserName: [
                    { required: true, message: '请输入开户人姓名' }
                ],
                bankCode: [
                    { required: true, message: '请输入银行卡号' }
                ]
            },
            agentLevels: [],
            agentList: []
        }
    },
    mounted() {
        this.searchAgentHander()
        this.getAllAgentLevel()
    },
    methods: {
        //显示
        open(mode = 'add') {
            this.mode = mode;
            this.stepActive = 1;
            if (mode == 'add') {
                this.resetForm()
            }
            this.visible = true;
            return this
        },
        getAllAgentLevel() {
            this.$API.agent.level.all.get({}).then(res => {
                this.agentLevels = res.data
            })
        },
        resetForm() {
            this.form = this.getDefaultRuleForm()
        },
        nextHander() {
            if (this.stepActive < this.totalStep) {
                this.stepActive ++;
            }
        },
        prevHander() {
            if (this.stepActive > 0) {
                this.stepActive = this.stepActive - 1;
            }
        },
        levelChangeHander(row) {
            this.agentLevels.forEach(item => {
                if (item.id == row) {
                    this.form.classHour60 = item.classHourSixty
                    this.form.amount = item.amount
                }
            })
        },
        submit() {
            this.$refs.dialogForm.validate(async (valid) => {
                if (!valid) {
                    return false
                }

                let data = {}
				for(let key in this.form) {
                    if (key == 'region') {
                        if (this.form[key].length == 1) {
                            data['provinceId'] = this.form[key][0]
                            data['cityId'] = 0
                            data['countyId'] = 0
                        }else if (this.form[key].length == 2) {
                            data['provinceId'] = this.form[key][0]
                            data['cityId'] = this.form[key][0]
                            data['countyId'] = this.form[key][1]
                        }else{
                            data['provinceId'] = this.form[key][0]
                            data['cityId'] = this.form[key][1]
                            data['countyId'] = this.form[key][2]
                        }
                        continue
                    }
					data[key] = this.form[key]
				}

                //身份证正反面处理
				let _idCardImg = []
				if (data.idCardImg && typeof(data.idCardImg) === 'string') {
					data.idCardImg.split(",").forEach(item => {
						item && _idCardImg.push(item.match(/.+\.com(.+)/)[1])
					})
				} else if(data.idCardImg && data.idCardImg.length > 0) {
					data.idCardImg.forEach((item) => {
						_idCardImg.push(item.path)
					})
				}
				data.idCardImg = _idCardImg

                try {
                    this.isSaveing = true;
                    await this.$API.agent.audit.action.post(data).then(res => {
                            this.isSaveing = false;
                            if (res.error == 0) {
                                this.visible = false
                                this.$emit('success')
                                this.$notify.success("保存成功")
                            }else {
                                this.$notify.error(res.message)
                            }
                    })
                } catch (error) {
                    this.isSaveing = false;
                }
            })
        },
        //表单注入数据
        async setData(row) {
            this.loading = true
			await this.$API.agent.audit.action.get({id: row.id}).then(res => {
                let _data = res.data
                let _form = {
                        levelId: _data.level ? parseInt(_data.level.id) : '',
                        parentId: _data.parent ? parseInt(_data.parent.id) : '',
                        image: _data.image ? _data.image.url : '',
                        name: _data.name,
                        amount: _data.amount,
                        manager: _data.manager,
                        managerMobile: _data.managerMobile,
                        managerIdCard: _data.managerIdCard,
                        chargeName: _data.chargeName,
                        chargeMobile: _data.chargeMobile,
                        chargeIdCard: _data.chargeIdCard,
                        provinceId: _data.province ? _data.province.id : 0,
                        cityId: _data.city ? _data.city.id : 0,
                        countyId: _data.county ? _data.county.id : 0,
                        address: _data.address,
                        promoterName: _data.promoterName,
                        promoterMobile: _data.promoterMobile,
                        idCardImg: [],
                        promoterImg: _data.promoterImg && _data.promoterImg.path ? _data.promoterImg.url : '',
                        paymentImg: _data.paymentImg && _data.paymentImg.path ? _data.paymentImg.url : '',
                        contractImg: _data.contractImg && _data.contractImg.path ? _data.contractImg.url : '',
                        classHour60: _data.classHour60,
                        bankFullName: _data.bankFullName,
                        bankUserName: _data.bankUserName,
                        bankCode: _data.bankCode
                }

                if(_form.provinceId && !_form.cityId && !_form.countyId) {
                    _form.region = [_form.provinceId]
                }else if (_form.provinceId == _form.cityId) {
                    _form.region = [_form.provinceId, _form.countyId]
                }else{
                    _form.region = [_form.provinceId, _form.cityId, _form.countyId]
                }

                if (_data.idCardImg && _data.idCardImg.length > 0) {
                    let images = []
                    _data.idCardImg.forEach(item => {
                        item.url && images.push(item.url)
                    })
                    _form.idCardImg = images.join(",")
                }

                this.form = _form
            }).finally(() => {
				this.loading = false
			})
        },
        getDefaultRuleForm() {
            return {
                id: 0,
                levelId: "",
                parentId: "",
                image: "",
                name: "",
                amount: "",
                manager: "",
                managerMobile: "",
                managerIdCard: "",
                chargeName: "",
                chargeMobile: "",
                chargeIdCard: "",
                provinceId: 0,
                cityId: 0,
                countyId: 0,
                address: "",
                promoterName: "",
                promoterMobile: "",
                idCardImg: [],
                promoterImg: "",
                paymentImg: "",
                contractImg: "",
                classHour60: "",

                // 提现账户
                bankFullName: "",
                bankUserName: "",
                bankCode: ""
            }
        },
        searchAgentHander(query) {
            this.agentLoading = true;
            this.$API.agent.listByName.get({name:query}).then((res) => {
                this.agentList = res.data
            }).finally(() => {
                this.agentLoading = false
            });
        },
        parentAgentChangeHander(row) {
            const agent = this.agentList.find(item => item.id == row)
            if (agent?.level?.id == 12) {
                const levels = []
                // 一级合伙人只能添加一级合伙人
                this.agentLevels.forEach(item => {
                    if (item.id != 11) {
                        levels.push(item)
                    }
                })
                this.agentLevels = levels
            }else {
                this.getAllAgentLevel()
            }
        }
    }
}
</script>

<style lang="scss">
.el-tag {
    margin-left: 0 !important;
    margin-right: 10px !important;
}
::v-deep.ck.ck-editor__main>.ck-editor__editable {
    height: 200px !important;
}

.custom-box {
  position: fixed;
  width: 970px;
  height: 120px;
  background-color: #fff;
  z-index: 100;
  margin-top: -40px;
  padding-top: 40px;
}

.cotent {
  padding-top: 80px;
  padding-right: 20px;
  height: 100%;
}
</style>
